﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;
using Spinning.Spinning.Unitity;
using System.Collections.ObjectModel;
using com.google.zxing.qrcode;
using Microsoft.Devices;
using com.google.zxing.common;
using com.google.zxing;
using System.Windows;
using System.Windows.Threading;
using Microsoft.Xna.Framework.Graphics;


namespace Spinning.Spinning.Entity.Scenes
{
    class QRreaderScene :BaseScene
    {
        TextEntity te;
        private DispatcherTimer _timer;
        private ObservableCollection<string> _matches;

        private PhotoCameraLuminanceSource _luminance;
        private QRCodeReader _reader;
        private PhotoCamera _photoCamera;
        System.Windows.Media.VideoBrush _previewVideo;


        public QRreaderScene()
            : base()
        {
            Size = new Vector2(1);
        }

        public override void OnLoad()
        {
            base.OnLoad();
            te = new TextEntity();
            ResourceManager.ContentRoot = "";
            te.fontString = "TestFont";
            te.OnLoad();
            te.Origin = new Vector2(0.5f);
            te.Position = new Vector2(200, 200);
            te.Color = Color.Blue;
            //te.Alpha = 0;
            te.ZIndex = Constants.debugText;
            Attach(te);

            _matches = new ObservableCollection<string>();

            _timer = new DispatcherTimer();
            _timer.Interval = TimeSpan.FromMilliseconds(250);
            _timer.Tick += (o, arg) => ScanPreviewBuffer();

            _photoCamera = new PhotoCamera();
            _photoCamera.Initialized += OnPhotoCameraInitialized;
            _previewVideo = new System.Windows.Media.VideoBrush();
            
            _previewVideo.SetSource(_photoCamera);
            
            CameraButtons.ShutterKeyHalfPressed += (o, arg) => _photoCamera.Focus();
        }

        private void OnPhotoCameraInitialized(object sender, CameraOperationCompletedEventArgs e)
        {
            int width = Convert.ToInt32(_photoCamera.PreviewResolution.Width);
            int height = Convert.ToInt32(_photoCamera.PreviewResolution.Height);

            _luminance = new PhotoCameraLuminanceSource(width, height);
            _reader = new QRCodeReader();

            _previewVideo.Dispatcher.BeginInvoke(() =>
            {
                //this.Rotation = (float)_photoCamera.Orientation;
                _timer.Start();
            });
        }

       

        private void ScanPreviewBuffer()
        {
            try
            {
                _photoCamera.GetPreviewBufferY(_luminance.PreviewBufferY);
                var binarizer = new HybridBinarizer(_luminance);
                var binBitmap = new BinaryBitmap(binarizer);
                var result = _reader.decode(binBitmap);
                _previewVideo.Dispatcher.BeginInvoke(() => DisplayResult(result.Text));
            }
            catch
            {
            }
        }

        private void DisplayResult(string text)
        {
            if (!_matches.Contains(text))
                _matches.Add(text);
            te.Value = text;
            stopCamera();
            GoToScene();
        }

        void stopCamera()
        {
            //dispose PhotoCamera
            if (_photoCamera != null)
                _photoCamera.Dispose();
            _photoCamera = null;
        }

        void GoToScene() 
        {
            Game1.stageManager.GoToScene("menu");
        }


        public override BaseScene Clone()
        {
            BaseScene scene = new QRreaderScene();
            scene.Size = new Vector2(Constants.Window_Width, Constants.Window_Height);
            scene.OnLoad();
            scene.SortChildren();
            return scene;
        }
    }
}
